package com.example.hiltapplication.ui

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.bodycontrolmoduledomain.SkyWinUiState
import com.example.bodycontrolmoduledomain.SkyWindowUseCase
import com.example.bodycontrolmoduledomain.TailGateCases
import com.example.bodycontrolmoduledomain.TailGateUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import javax.inject.Inject
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch


/**
 * ViewModel注解  作为 hilt依赖树的入口节点 enterPoint
 * */
@HiltViewModel
class MainViewModel
 @Inject constructor(
    private val skyWindowUiStateTransferCase: SkyWindowUseCase,
    private val tailGateCases:TailGateCases
): ViewModel() {
    private val TAG = "MainViewModel"

    data class PageUiState(
        val skyUiState:SkyWinUiState,
        val tailgateUiState: TailGateUiState
    )

    private val _mutablePageUiState : MutableStateFlow<PageUiState> = MutableStateFlow(
        PageUiState(
            SkyWinUiState(),
            TailGateUiState()
        )
    )
    val pageUiState:StateFlow<PageUiState> = _mutablePageUiState.asStateFlow()

    /**
     * 通过网域层暴露的接口或属性，获取截面数据的stateFlow
     * 使用不可变类型的flow 严格限制数据在非业务侧的改动
     * */
    private val skyUiStateFlow:StateFlow<SkyWinUiState> =  skyWindowUiStateTransferCase.skyWinStateFlow

    /**
     * 另一个网域层的数据
     * */
    private val tailGateStateFlow:StateFlow<TailGateUiState> = tailGateCases.tailGateStateFlow

    init {
        Log.i(TAG, "viewMode constructor: ")

        /**
         * 在viewModelScope 创建一个协程 使用Default线程
         * 在这个协程中进行domain层的数据监听
         * */
        viewModelScope.launch(Dispatchers.Default) {
            combine(skyUiStateFlow,tailGateStateFlow){skyUiState,tailGateUiState->
                PageUiState(skyUiState,tailGateUiState)
            }.collect{
                _mutablePageUiState.emit(it)
            }
        }
    }


    fun setSkyWindowPos(pos:Int) {
        Log.i(TAG, "setSkyWindowPos: $pos")
        skyWindowUiStateTransferCase.invoke(pos)
    }


    fun openTailGate() {
        tailGateCases.openTailGate()
    }

    fun closeTailGate() {
        tailGateCases.closeTailGate()
    }

    fun setTailGatePos(progress: Int) {
        tailGateCases.setTailGatePos(progress)
    }

    fun skyWinClicked() {
        skyWindowUiStateTransferCase.skyWinClicked()
    }

}